package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.member.MacroAppLoginDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IMcroAppLoginService;
import com.zzyl.nursing.vo.member.MacroAppLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2025/5/23 14:41
 * @Version 1.0
 */
@Slf4j
@Service
public class McroAppLoginServiceImpl implements IMcroAppLoginService {

    private final static String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private final static String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token= ";


    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private TokenService tokenService;

    @Override
    public MacroAppLoginVo login(MacroAppLoginDto dto) {
        //1.通过code 获取Openid
        String openId = getOpenId(dto.getCode());
        if(!StringUtils.hasText(openId)){
            log.error("openid为空");
            throw new BaseException("登录异常");
        }
        //2.判断是否新用户
        LambdaQueryWrapper<FamilyMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FamilyMember::getOpenId,openId);
        FamilyMember familyMember = familyMemberMapper.selectOne(wrapper);
        //3.如果是新用户，我就去拿他的手机号
        if(familyMember == null){
            familyMember = new FamilyMember();
            String phone = getPhone(dto.getPhoneCode());
            familyMember.setCreateTime(new Date());
            familyMember.setPhone(phone);
            familyMember.setOpenId(openId);
            familyMember.setName("花开富贵");

            familyMemberMapper.insert(familyMember);
        }
        //4.生成token，封装返回数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",familyMember.getId());
        map.put("openId",openId);
        String token = tokenService.createToken(map);
        MacroAppLoginVo vo = MacroAppLoginVo.builder().token(token).nickName(familyMember.getName()).build();
        return vo;
    }

    /**
     * 获取手机号
     * @param phoneCode
     * @return
     */
    private String getPhone(String phoneCode){
        String token = getToken();
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",phoneCode);
        String response = HttpUtil.post(PHONE_URL + token, JSONUtil.toJsonStr(param));
        log.info("获取手机号返回：{}",response);
        JSONObject jsonObject = JSONUtil.parseObj(response);
        String phone = (String)JSONUtil.getByPath(jsonObject, "phone_info.phoneNumber");
        return phone;
    }

    /**
     * 获取调用凭证
     * @return
     */
    private String getToken(){
        HashMap<String, Object> param = new HashMap<>();
        param.put("grant_type","client_credential");
        param.put("appid",appId);
        param.put("secret",secret);
        String response = HttpUtil.get(TOKEN_URL, param);
        log.info("获取调用令牌返回：{}",response);
        return JSONUtil.parseObj(response).getStr("access_token");
    }


    /**
     * 获取用户openId
     * @param code
     * @return
     */
    private String getOpenId(String code){
        Map<String,Object> param = new HashMap<>();
        param.put("appid",appId);
        param.put("secret",secret);
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        String response = HttpUtil.get(LOGIN_URL, param);
        log.info("获取微信openid返回：{}",response);
        JSONObject jsonObject = JSONUtil.parseObj(response);
        return jsonObject.getStr("openid");
    }
}